import getApiData, { getApisData, getApisDataOfApiKey, getNestApiData } from "@/services/cpasRequest";
import { SampleStepInfo, SampleParameterValues, SampledResult, ManualSampleParams, SampledNumFields, TypedSampleInfo, SampleTable, WhereSqlParams, ProjectOverallProps, SamplingSampleListProps, SampleType, SampleField, SampleListTimes, TypedSampleTextFieldValues } from "../typing";
import { getTextFieldsValues, getToBeTestWhereSql, getWhereSqlBySampleList, getWhereSqlBySampleListOfTable } from "./SampleParameter/NonStatSampleService";
import { consts } from "../consts";
import { getRealTableName, getRealTableName_sampleList } from "./service";
import { msgError } from "@/utils/msg";
import { getSampleOverallWhereSQL } from "./samplingProjectOverallService";

/**
 * 获取所有已抽的条件(界面条件不包含),抽样+金额重大+特殊项目
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 */
export function getAllSampledWhereSql(sampleParameterValues: SampleParameterValues, sampledWhereSql: string) {
    // let sampledResult: SampledResult = sampleParameterValues.sampledResult as any;



    let sampleListManualAddWhereSql = sampleParameterValues.manualAddParams?.manualWhereSql;

    let allSampledWhereSql = '  /*getAllSampledWhereSql:*/ and (1=0 '
    //金额重大项目
    if (sampleParameterValues.amountMajorWhereSql) {

        allSampledWhereSql += ` or  (1=1  ${sampleParameterValues.amountMajorWhereSql}) `;
    }
    //特殊项目
    if (sampleParameterValues.specialWhereSql) {
        allSampledWhereSql += ` or (1=1  ${sampleParameterValues.specialWhereSql})`
    }
    //抽样方法抽样的
    if (sampledWhereSql) {
        allSampledWhereSql += ` or  (1=1  ${sampledWhereSql}) `;
    }
    if (sampleListManualAddWhereSql) {
        allSampledWhereSql += `  or (1=1 ${sampleListManualAddWhereSql})`;//样本列表界面手工增加的
    }
    allSampledWhereSql += `)`
    //返回 获取所有已抽的条件,抽样+金额重大+特殊项目
    return allSampledWhereSql;
}
/**
 * 未抽样的样本列表条件
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 * @returns 
 */
export async function getNotSampleWhereSql(sampleStepInfo: SampleStepInfo,
    sampleParameterValues: SampleParameterValues, dbname: string) {

    let sampledResult: SampledResult = sampleParameterValues.sampledResult as any;

    let sampledWhereSql = await getWhereSqlBySampleListOfTable(sampleStepInfo, sampledResult.sampledList, dbname);
    //样本列表界面手工增加的
    let sampleListManualAddWhereSql = sampleParameterValues.manualAddParams?.manualWhereSql;

    if (!sampleParameterValues.toBeTestWhereSql) {
        sampleParameterValues.toBeTestWhereSql = getToBeTestWhereSql(sampleParameterValues)
    }
    //待测试的总体(条件排除 特殊|金额重大)
    let notSampleWhereSql = ' /*getNotSampleWhereSql:*/ ' + (sampleParameterValues.toBeTestWhereSql || '')
    //已抽样的
    if (sampledWhereSql) {
        notSampleWhereSql += ` and not  ( 1=1  ${sampledWhereSql})`;
    }
    //样本列表界面手工增加的
    if (sampleListManualAddWhereSql) {
        notSampleWhereSql += ` and not  ( 1=1  ${sampleListManualAddWhereSql})`;
    }
    //返回 获取所有已抽的条件,抽样+金额重大+特殊项目
    return notSampleWhereSql;
}
/**
 * 新加或删除后,更新手工增加样本的参数
 * @param manualAddParams  手工增的样本参数
 * @param sampleStepInfo  抽样步骤信息
 * @param sampleParameterValues  抽样参数
 * @param textFieldsArray 文本字段
 * @param numFieldsArray 数字字段
 */
export async function updateManualAddParams(props: SamplingSampleListProps, manualAddParams: ManualSampleParams,
    sampleStepInfo: SampleStepInfo, sampleParameterValues: SampleParameterValues,
    textFieldsArray: string[], numFieldsArray: string[]) {
    manualAddParams.sampledList.forEach((item, index) => item.rn = index + 1)

    const sampledNumFields: SampledNumFields = manualAddParams.sampledNumFields || {};
    const sampledList = manualAddParams.sampledList
    const sampledSize = sampledList.length; //newSpecialSampleList.length;
    const sampleTextFieldValues = sampledList.map(item => getTextFieldsValues(item, textFieldsArray));
    let sampledAmountSum = 0;
    numFieldsArray.forEach(fieldName => {
        const amountSum = sampledList.reduce((sum, item) => {
            return sum + Math.abs(Number(item[fieldName] || 0))
        }, 0)
        sampledAmountSum += amountSum;
        sampledNumFields[fieldName] = { amountSum: amountSum }
    })

    const sampledResult: SampledResult = { sampledNumFields, sampledList, sampledSize, sampledAmountSum, sampleTextFieldValues }
    const manualWhereSql = await getWhereSqlBySampleList(sampleStepInfo, sampledList)

    sampleParameterValues.manualAddParams = { ...sampledResult, manualWhereSql };

    //手工样本
    /*  const typedSampleInfo = await getTypedSampleList(sampleStepInfo, sampleParameterValues, true)
     props.setTypedSampleInfo && props.setTypedSampleInfo({
         ...props.typedSampleInfo,
         manualAddSampleList: typedSampleInfo.manualAddSampleList,
         manualAddSampleTextFieldValues: typedSampleInfo.manualAddSampleTextFieldValues,
     }); */


}
/**
 * 样本分类列表
 */
export function getIniTypedSampleInfo(): TypedSampleInfo {
    return {
        specialSampleList: [],//特殊样本
        amountMajorSampleList: [],// 金额重大样本列表
        manualAddSampleList: [],// 手动添加样本列表

        specialSampleTextFieldValues: [],//特殊样本
        amountMajorSampleTextFieldValues: [],// 金额重大样本列表
        manualAddSampleTextFieldValues: [],// 手动添加样本列表
    }
}
/**
 * 是否有值
 * @param typedSampleInfo 
 */
export function getTypedSampleInfoIsIniValue(typedSampleInfo: any /* TypedSampleInfo */) {
    if (!typedSampleInfo) return true;
    let cnt = Object.keys(typedSampleInfo).reduce((sum, key) => {
        return sum + (typedSampleInfo[key]?.length || 0)
    }, 0)
    return cnt == 0
}
/**
 * 获取样本类型
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 */
export async function getTypedSampleList(sampleStepInfo: SampleStepInfo,
    sampleParameterValues: SampleParameterValues, isOnlyManualAdd: boolean): Promise<TypedSampleInfo> {

    const typedSampleList = getIniTypedSampleInfo();
    const projectOverallProps: ProjectOverallProps = sampleStepInfo.projectOverallProps as any;
    const curSampleTable: SampleTable = projectOverallProps.curSampleTable as any;
    const curWhereSqlParams: WhereSqlParams = projectOverallProps.curWhereSqlParams as any;
    const textFieldsArray: string[] = curSampleTable.sampleTextFieldsArray || [];
    // const numFieldsArray: string[] = curSampleTable.sampleNumFieldsArray || [];
    const sortFieldsArray: string[] = curSampleTable.sortFieldsArray || [];
    const apis: any = {};
    
    //如果非仅手工增加,则获取特殊项目,金额重大的样本
    if (!isOnlyManualAdd) {
        if (sampleParameterValues.specialWhereSql) {
            apis[SampleType.special] = {
                params: {
                    sampleType: SampleType.special,
                    whereSql: sampleParameterValues.specialWhereSql
                }
            }
        }
        if (sampleParameterValues.amountMajorWhereSql) {
            const sampleWhereSQL = getSampleOverallWhereSQL(projectOverallProps?.curWhereSqlParams as WhereSqlParams)
            apis[SampleType.amountMajor] = {
                params: {
                    sampleType: SampleType.amountMajor,
                    whereSql: sampleWhereSQL + sampleParameterValues.amountMajorWhereSql
                }
            }
        }
    }

    //手工增加
    if (sampleParameterValues.manualAddParams?.manualWhereSql) {
        apis[SampleType.manualAdd] = {
            params: {
                sampleType: SampleType.manualAdd,
                whereSql: sampleParameterValues.manualAddParams?.manualWhereSql
            }
        }
    }

    if (Object.keys(apis).length == 0) {
        console.error('getTypedSampleList方法中,Object.keys(apis).length==0')
        return typedSampleList;
    }

    for (const key in apis) {
        apis[key].name = 'sample.getSampleSourceDataList'
    }

    const postData = {
        apis,
        reload: true,
        params: {
            dbname: curWhereSqlParams?.dbname,
            pageIndex: 0,
            pageSize: consts.maxSampleCount,
            tableName: getRealTableName(projectOverallProps?.curSampleTable?.tableName || '',
                { data_id: projectOverallProps?.curDataId || '' }),//todo:要替换真值
            sortFields: sortFieldsArray.length ? sortFieldsArray.map(item => `[${item}]`).join(',')
                : consts.selectNullOrderFields,
            fields: textFieldsArray.length ? textFieldsArray.map(fieldName => `[${fieldName}]`).join(',') : '*',
        }
    }
    //批量执行
    const retData = await getApisDataOfApiKey(postData);
    if (!retData.ok) {
        msgError(retData.data)
    }


    for (const key in apis) {
        const retDataSub = retData.data[key];
        if (retDataSub.ok) {
            if (key == SampleType.special) {
                typedSampleList.specialSampleList = retDataSub.data;
                typedSampleList.specialSampleTextFieldValues = typedSampleList.specialSampleList.map(item => getTextFieldsValues(item, textFieldsArray))
            } else if (key == SampleType.amountMajor) {
                typedSampleList.amountMajorSampleList = retDataSub.data;
                typedSampleList.amountMajorSampleTextFieldValues = typedSampleList.amountMajorSampleList.map(item => getTextFieldsValues(item, textFieldsArray))
            } else if (key === SampleType.manualAdd) {
                typedSampleList.manualAddSampleList = retDataSub.data;
                typedSampleList.manualAddSampleTextFieldValues = typedSampleList.manualAddSampleList.map(item => getTextFieldsValues(item, textFieldsArray))
            }
        }
    }

    return typedSampleList;
}
/**
 * 更新样本一个类型
 */
export function updateOneSampleType(textFieldValues: string[], rowsData: any[], textFieldsArray: string[], sampleType: SampleType) {
    if (textFieldValues?.length) {
        const foudRowsData = rowsData.filter(item => {
            const values = getTextFieldsValues(item, textFieldsArray);
            return textFieldValues.includes(values)
        })
        foudRowsData.forEach(item => {
            if (item.sampleType) {
                if (!item.sampleType.includes(sampleType)) {
                    item.sampleType = item.sampleType + ',';
                }
            } else {
                item.sampleType = '';
            }
            if (!item.sampleType.includes(sampleType)) {
                item.sampleType += sampleType
                // item.sampleFrequency = item.sampleFrequency + 1;//抽样次数+1
            }
        })
    }
}
/**
 * 更新样本全部类型:金额重大/特殊样本/手工增加/正常样本
 * @param TypedSampleInfo 
 * @param rowsData 
 * @param textFieldsArray 
 */
export function updateAllSampleType(typedSampleInfo: TypedSampleInfo, rowsData: any[], textFieldsArray: string[],
    sampleListTimes: SampleListTimes[]) {
    const { specialSampleTextFieldValues, amountMajorSampleTextFieldValues, manualAddSampleTextFieldValues } = typedSampleInfo;
    console.time('updateAllSampleType')
    rowsData.forEach(item => item.sampleFrequency = 0);//抽样次数初始为0
    if (sampleListTimes.length == 0) {
        //更新样本类型--金额重大
        updateOneSampleType(amountMajorSampleTextFieldValues, rowsData, textFieldsArray, SampleType.amountMajor)

        //更新样本类型--特殊样本
        updateOneSampleType(specialSampleTextFieldValues, rowsData, textFieldsArray, SampleType.special)

        //更新样本类型--手工增加
        updateOneSampleType(manualAddSampleTextFieldValues, rowsData, textFieldsArray, SampleType.manualAdd)

        //正常样本
        rowsData.filter(item => !item.sampleType).forEach(item => item.sampleType = SampleType.normal)
    }

    const allSampleTextFieldValues = amountMajorSampleTextFieldValues.concat(specialSampleTextFieldValues, manualAddSampleTextFieldValues)

    const newSampleListTimes = sampleListTimes;// sampleListTimes.filter(item => !allSampleTextFieldValues.includes(item.textFieldValues));

    rowsData.forEach(item => {
        const textValues = getTextFieldsValues(item, textFieldsArray);
        if (sampleListTimes.length) {
            let normalTimes = newSampleListTimes.find(item => item.textFieldValues == textValues)
            item.sampleFrequency = normalTimes?.times || 1;
            item.sampleType = normalTimes?.sampleType;
        } else {
            let times = allSampleTextFieldValues.filter(fieldValues => fieldValues == textValues).length;

            //普通样本=所有样本-特殊(样本)-金额重大项目-手工
            let normalTimes = newSampleListTimes.find(item => item.textFieldValues == textValues)
            times += normalTimes?.times || 0;

            if (times == 0) {
                times = (item.sampleType + '').split(',').length
            }
            item.sampleFrequency = times;
        }

    });//抽样次数计算
    rowsData.forEach(item => { if (!item.sampleType) item.sampleType = SampleType.normal });
    console.timeEnd('updateAllSampleType')
}
/**
 * 更新样本表的isChecked字段
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 */
export async function updateTableIsChecked(sampleStepInfo: SampleStepInfo,
    sampleParameterValues: SampleParameterValues, isChecked: boolean,
    dbname: string): Promise<boolean> {
    const projectOverallProps: ProjectOverallProps | undefined = sampleStepInfo.projectOverallProps

    if (projectOverallProps?.curSampleTable) {//
        //查询条件
        const sampleOverallWhereSQL = projectOverallProps.curWhereSqlParams ? getSampleOverallWhereSQL(projectOverallProps.curWhereSqlParams) : '';//获取sql
        //抽样样本条件(已抽样的条件)
        const { sampledWhereSql } = await getWhereSqlBySampleListOfTable(sampleStepInfo,
            sampleParameterValues.sampledResult?.sampledList || [], dbname)

        const allSampledWhereSql = getAllSampledWhereSql(sampleParameterValues, sampledWhereSql);
        const textFieldsArray = projectOverallProps?.curSampleTable.sampleTextFieldsArray;

        const parmas = {
            dbname: projectOverallProps.curWhereSqlParams?.dbname,
            tableName: getRealTableName(projectOverallProps?.curSampleTable?.tableName || '',
                { data_id: projectOverallProps?.curDataId || '' }),
            bFields: textFieldsArray.map(fieldName => `[${fieldName}]`).join(','),//b表的字段
            bWhereSql: sampleOverallWhereSQL + allSampledWhereSql,//b表的whereSql
            relateWhereSql: ' and ' + textFieldsArray.map(fieldName => `a.[${fieldName}]=b.[${fieldName}]`).join(' and '),
            countGt1RelateWhereSql: ' and ' + textFieldsArray.map(fieldName => `countGt1.[${fieldName}]=b.[${fieldName}]`).join(' and '),
            isChecked: isChecked ? 1 : 0,//是否选中
            recordGuid: sampleStepInfo.guid,//
            allSampleRecordTable: getRealTableName_sampleList(projectOverallProps.curSampleTable.tableName,
                { data_id: projectOverallProps.curDataId })

        }
        const retData = await getApiData('sample.updateTableIsChecked', parmas);
        if (!retData.ok) {
            msgError(retData.data)
        }
        return retData.ok
    } else {
        return true;
    }
}
/**
* 创建所有样本关键字段的表(多次执行,自动增加字段)
* @param dbname 
* @param all_sample_record_table 
* @param sampleTextSampleFieldsArray 
* @returns 
*/

export async function createAllSampleListTable(sampleStepInfo: SampleStepInfo, dbname: string) {

    const projectOverallProps: ProjectOverallProps | undefined = sampleStepInfo.projectOverallProps;
    //const sampleTextFieldsArray = projectOverallProps?.curSampleTable?.sampleTextFieldsArray;
    return createAllSampleListTableBySampleTable(projectOverallProps?.curSampleTable, dbname, projectOverallProps?.curDataId)
}

/**
 * 创建所有样本关键字段的表(多次执行,自动增加字段)

 * @param curSampleTable 
 * @param dbname 
 * @param dataId 
 * @returns 
 */
export async function createAllSampleListTableBySampleTable(curSampleTable?: SampleTable, dbname?: string, dataId?: string) {

    const sampleTextSampleFieldsArray: SampleField[] = curSampleTable?.sampleAllFieldsArray
        .filter((item: any) => curSampleTable.sampleTextFieldsArray?.includes(item.fieldName)) || [];

    if (sampleTextSampleFieldsArray.length) {
        const allSampleRecordTable = getRealTableName_sampleList(curSampleTable?.tableName || '',
            { data_id: dataId || '' });
        const parmas = {
            dbname: dbname,
            allSampleRecordTable,
            sampleTextSampleFieldsArray,
        }
        const retData = await getNestApiData('/auditSample/createAllSampleListTable', 'POST', parmas);
        if (!retData.ok) {
            msgError('创建表错误:' + retData.data)
        }
        return retData.ok
    }
    return false;
}
/**
 * 获取所有样本的对象数组
 * @param sampleStepInfo 
 * @param typedSampleInfo 
 */
export function getAllSampleDataList(sampleStepInfo: SampleStepInfo, typedSampleInfo: TypedSampleInfo) {

    let allSampleDataList: any[] = getTypeSampleDataList(sampleStepInfo, typedSampleInfo.specialSampleList, SampleType.special)
        .concat(getTypeSampleDataList(sampleStepInfo, typedSampleInfo.amountMajorSampleList, SampleType.amountMajor))
        .concat(getTypeSampleDataList(sampleStepInfo, typedSampleInfo.manualAddSampleList, SampleType.manualAdd))
        .concat(getTypeSampleDataList(sampleStepInfo, sampleStepInfo.sampleParameterValues?.sampledResult?.sampledList || [], SampleType.normal));
    return allSampleDataList;
}
/**
 * 插入分类样本信息
 * @param sampleStepInfo 
 * @param dbname 
 * @param typedSampleTextFieldValues 
 * @returns 
 */
export async function insertAllSampleListTable(sampleStepInfo: SampleStepInfo, dbname: string,
    allSampleDataList: any[], recordGuid: string) {

    const projectOverallProps: ProjectOverallProps | undefined = sampleStepInfo.projectOverallProps;
    const sampleTextFieldsArray = projectOverallProps?.curSampleTable?.sampleTextFieldsArray;

    const sampleTextSampleFieldsArray: SampleField[] = projectOverallProps?.curSampleTable?.sampleAllFieldsArray
        .filter((item: any) => sampleTextFieldsArray?.includes(item.fieldName)) || [];

    if (sampleTextSampleFieldsArray.length) {
        const allSampleRecordTable = getRealTableName_sampleList(projectOverallProps?.curSampleTable?.tableName || '',
            { data_id: projectOverallProps?.curDataId || '' });
        const parmas = {
            dbname: dbname,
            allSampleRecordTable,
            allSampleDataList,
            recordGuid,
            sampleTextSampleFieldsArray,
        }
        const retData = await getNestApiData('/auditSample/insertAllSampleListTable', 'POST', parmas);
        if (!retData.ok) {
            msgError('保存表数据错误:' + retData.data)
        }
        return retData.ok
    }
    return false;
}
/**
 * 获取样本抽样次数列表
 * @param sampleStepInfo 
 * @param dbname 
 * 返回 {fields},times
 */
export async function getSampleListTimes(dbname: string, curSampleTable?: SampleTable, curDataId?: string)
    : Promise<SampleListTimes[]> {
    const fields = curSampleTable?.sampleTextFields;
    const sampleTextFieldsArray = curSampleTable?.sampleTextFieldsArray;
    if (!sampleTextFieldsArray?.length) {
        msgError('表还没有配置抽样项目字段,请到样本源中配置');
        return [];
    }

    //增加字段 以免字段抽样改变
    await createAllSampleListTableBySampleTable(curSampleTable, dbname, curDataId);

    const retData = await getApiData('sample.getSampleListTimes', {
        dbname,
        allSampleRecordTable: getRealTableName_sampleList(curSampleTable?.tableName || '',
            { data_id: curDataId || '' }),
        fields,
        relateCondition: sampleTextFieldsArray.map(field => `a.[${field}]=b.[${field}]`).join(' and ')
    })

    if (!retData.ok) {
        msgError('获取样本抽样次数列表错误:' + retData.data);
        return [];
    }
    return (retData.data as any[]).map(item => {
        return {
            textFieldValues: getTextFieldsValues(item, sampleTextFieldsArray || []),
            times: item.times,
            sampleType: item.sample_type,
        }
    });
}
/**
 * 获取分类样本数
 * @param sampleStepInfo 
 * @param sampleList 
 * @param sampleType 
 * @returns 
 */
export function getTypeSampleDataList(sampleStepInfo: SampleStepInfo, sampleList: any[], sampleType: SampleType) {
    const projectOverallProps: ProjectOverallProps | undefined = sampleStepInfo.projectOverallProps;
    const sampleTextFieldsArray = projectOverallProps?.curSampleTable?.sampleTextFieldsArray;
    return sampleList.map(item => {
        const data: any = {
            sample_type: sampleType,
            record_guid: sampleStepInfo.guid,
        };
        sampleTextFieldsArray?.forEach(fieldName => data[fieldName] = item[fieldName])
        return data;
    });
}